<template>
  <div class="authentication page" ref="webview">
    <div class="nav-bar">
      <van-nav-bar left-arrow class="bg_white" @click-left="$router.push({'path':'/my'})" :title="!typeFrom ? '实名认证':'实名信息'" />
    </div>
    <div class="content">
      <div class="id-name">身份信息</div>
      <div class="id-from">
        <van-field v-model="form.fullName " label="姓名" :disabled="typeFrom" input-align="right " clearable placeholder="请输入姓名" />
        <van-field v-model="form.IDNumber" label="身份证" :disabled="typeFrom" input-align="right " clearable placeholder="请输入15位或18位身份证号码" />
      </div>
      <div class="id-name">
        身份信息
      </div>
      <div class="id-images">
        <div class="tis">
          请拍摄并上传你的身份证照片
        </div>
        <div class="positive-reverse">
          <div class="positive">
            <template v-if="!typeFrom">
              <template v-if="isApp">
                <div class="images hidden" @click="openAction('1')">
                  <template v-if="form.frontImg">
                    <img :src="form.frontImg" @click.stop="showIMG('1')" v-if="form.frontImg" />
                  </template>
                </div>
                <span class="van-icon van-icon-clear van-uploader__preview-delete" v-if="form.frontImg" @click="removeImg('1')"></span>
              </template>
              <template v-else>
                <div class="images">
                  <van-uploader class="uploader" name="frontImg" v-model="frontImgList" :after-read="afterRead" :max-count="1" />
                </div>
              </template>
              <div class="loading" v-if="isFrontLoading">
                <van-loading size="24px" color="#ffffff"></van-loading>
              </div>
            </template>
            <template v-else>
              <div class="images hidden">
                <img :src="form.frontImg" @click="showIMG('1')" v-if="form.frontImg" />
              </div>
            </template>
            <div class="text">{{!typeFrom?'拍摄正面':'正面'}}</div>
            <span class="camera" v-if="!form.frontImg && frontImgList.length== 0"></span>
          </div>
          <div class="reverse">
            <template v-if="!typeFrom">
              <template v-if="isApp">
                <div class="images hidden" @click="openAction('2')">
                  <template v-if="form.reverseImg">
                    <img :src="form.reverseImg" v-if="form.reverseImg" />
                  </template>
                </div>
                <span class="van-icon van-icon-clear van-uploader__preview-delete" v-if="form.reverseImg" @click="removeImg('2')"></span>
              </template>
              <template v-else>
                <div class="images">
                  <van-uploader class="uploader" name="reverseImg" v-model="reverseImgList" :after-read="afterRead" :max-count="1" />
                </div>
              </template>
              <div class="loading" v-if="isReverseLoading">
                <van-loading size="24px" color="#ffffff"></van-loading>
              </div>
            </template>
            <template v-else>
              <div class="images hidden">
                <img :src="form.reverseImg" @click="showIMG('2')" v-if="form.reverseImg" />
              </div>
            </template>
            <div class="text">{{!typeFrom?'拍摄反面':'反面'}}</div>
            <span class="camera" v-if="!form.reverseImg && reverseImgList.length== 0"></span>
          </div>
        </div>
      </div>
    </div>
    <div class="submitBtn">
      <van-button class="btn" round v-if="!typeFrom" :loading="isLoading " @click.native="submit ">确认无误并提交</van-button>
      <van-button class="btn" round v-else @click.native="goAuth">重新上传实名信息</van-button>
    </div>
    <van-image-preview v-model="showPreview" closeable :showIndex="false" :class="{isApp:isApp}" v-if="isApp" :images="images" />
    <van-action-sheet v-model="isSex" :round="false " @select="selectSex" cancel-text="取消" :actions="sexActions" description="选择性别" />
    <van-action-sheet v-model="isAction" :round="false " @select="selectAction" cancel-text="取消" :actions="actions" description="上传身份证信息 " />
  </div>
</template>
<script>
export default {
  name: 'authentication',
  data () {
    return {
      isLoading: false,
      isAction: false,
      isSex: false,
      images: [],
      showPreview: false,
      isFrontLoading: false,
      isReverseLoading: false,
      frontImgList: [],
      testIMG: '',
      isFrontFailed: false,
      isReverseFailed: false,
      reverseImgList: [],
      imgType: '', // 区分打开的是相机还是相册
      actions: [
        { name: '拍照' },
        { name: '本机相册' }
      ],
      sexActions: [
        { name: '保密', value: 0 },
        { name: '男', value: 1 },
        { name: '女', value: 2 }
      ],
      validity: null,
      fileFormData: null,
      form: {
        fullName: '',
        sex: '',
        address: '',
        nation: '',
        IDNumber: '',
        signing: '',
        startDate: '',
        endDate: '',
        born: '',
        frontImg: '',
        reverseImg: ''
      }
    };
  },
  computed: {
    typeFrom () {
      return parseInt(this.$route.query.type) === 2;
    },
    isApp: {
      get () {
        return !!localStorage.getItem('isApp') || !!this.$route.query.isApp;
      }
    }
  },
  mounted () {
    this.typeFrom && this.memberCertQuery();
  },
  methods: {
    onCopy () {
      this.$toast('复制成功');
    },
    onError () {
      this.$toast('复制失败');
    },
    afterRead (data, detail) {
      var fileFormData = new FormData();
      var isID = this.imgType === '1' || detail.name === 'frontImg';
      var FiletypeName = null;
      var fileData = null;
      if (!this.isApp) {
        FiletypeName = data.content.replace(/data:image\/([^;]+).*/i, '$1');
      } else {
        fileData = 'data:image/' + detail + ';base64,' + data;
      }
      fileFormData.append('fileType', !this.isApp ? FiletypeName : detail);
      fileFormData.append('base64', !this.isApp ? data.content : fileData);
      fileFormData.append('type', 'idcard');
      fileFormData.append('other', isID ? 'front' : 'back');
      this.$set(this, isID ? 'isFrontLoading' : 'isReverseLoading', true); // loading加载
      // 非APP用web上传
      if (!this.isApp) {
        this.fileUploadAccountImg(fileFormData, detail.name);
      } else {
        return fileFormData;
      }
    },
    // 显示图片
    showIMG (data) {
      this.images = [data === '1' ? this.form.frontImg : this.form.reverseImg];
      this.showPreview = true;
    },
    removeImg (data) {
      this.$set(this.form, (data === '1' ? 'frontImg' : 'reverseImg'), '');
    },
    // 上传身份证
    fileUploadAccountImg (fileFormData, type) {
      this.$API.global.cardFileUpload(fileFormData).then(res => {
        if (res.code === 0) {
          var _res = res.data;
          if (type === '1' || type === 'frontImg') {
            if (!this.isApp) {
              this.frontImgList = [{ url: _res.src }];
            }
            this.$set(this.form, 'frontImg', _res.src);
            this.form.fullName = _res.name || '';
            this.form.IDNumber = _res.cardNo || '';
          } else {
            if (!this.isApp) {
              this.reverseImgList = [{ url: _res.src }];
            }
            this.$set(this.form, 'reverseImg', _res.src);
          }
          this.isFrontLoading = false;
          this.isReverseLoading = false;
        } else {
          this.$toast(res.message);
          this.isFrontLoading = false;
          this.isReverseLoading = false;
        }
      });
    },
    goAuth () {
      this.$set(this.form, 'frontImg', '');
      this.$set(this.form, 'reverseImg', '');
      this.$set(this.form, 'fullName', '');
      this.$set(this.form, 'IDNumber', '');
      this.frontImgList = [];
      this.reverseImgList = [];
      this.$router.push({ path: 'authentication', query: { type: 1 } });
    },
    getPicture (type) {
      window.api.getPicture({
        sourceType: type === 'camera' ? 'camera' : 'album', // 从相册中选择
        encodingType: 'jpg',
        mediaValue: 'pic',
        allowEdit: false,
        destinationType: 'base64', // 返回base64地址
        quality: 70,
        saveToPhotoAlbum: true
      }, (ret, err) => {
        this.isAction = false;
        var fileType = ret.base64Data.replace(/data:image\/([^;]+).*/i, '$1');
        var base64Data = ret.base64Data.replace(/^data:image\/\w+;base64,/, '');
        var fileFormData = this.afterRead(base64Data, fileType);
        this.fileUploadAccountImg(fileFormData, this.imgType);
      });
    },
    // 文件流转base64
    toBase64 (data, callbark) {
      var trans = window.api.require('trans');
      trans.decodeImgToBase64({
        imgPath: 'widget://' + data
      }, (ret, err) => {
        if (ret.status) {
          callbark && callbark(ret.base64Str.replace(/[\r\n]/g, ''));
        } else {
          console(JSON.stringify(err));
        }
      });
    },
    // 打开系统相册
    UIMediaScanner () {
      var UIAlbumBrowser = window.api.require('UIAlbumBrowser');
      UIAlbumBrowser.imagePicker({
        max: 1,
        showCamera: false,
        styles: {
          bg: '#fff',
          mark: {
            icon: '',
            position: 'bottom_left',
            size: 20
          },
          nav: {
            bg: 'rgba(0,0,0,0.6)',
            titleColor: '#fff',
            titleSize: 18,
            cancelColor: '#fff',
            cancelSize: 16,
            finishColor: '#fff',
            finishSize: 16
          }
        },
        rotation: true
      }, (ret) => {
        if (ret) {
          this.isAction = false;
          if (ret.eventType === 'nextStep') {
            var list = ret.list[0];
            this.toBase64(list.path, (base64Str) => {
              var fileFormData = this.afterRead(base64Str, list.suffix);
              this.fileUploadAccountImg(fileFormData, this.imgType);
            });

            UIAlbumBrowser.closePicker();
            // alert(JSON.stringify(ret));
          }
        }
      });
    },
    memberCertQuery () {
      this.$API.user.memberCertQuery().then(res => {
        var _res = res.data;
        if (!res.code) {
          this.$set(this.form, 'frontImg', _res.front_img);
          this.$set(this.form, 'reverseImg', _res.reverse_img);
          this.$set(this.form, 'fullName', _res.full_name);
          this.$set(this.form, 'IDNumber', _res.id_number);
          if (!this.isApp) {
            this.frontImgList = [{ url: _res.front_img }];
            this.reverseImgList = [{ url: _res.reverse_img }];
          }
        }
      });
    },
    selectSex (action, index) {
      this.sexValue = action.value;
      this.form.sex = action.name;
      this.isSex = false;
    },
    selectAction (action, index) {
      if (!index) {
        this.getPicture('camera');
      } else {
        this.UIMediaScanner();
      }
    },
    openAction (type) {
      this.imgType = type;
      this.isAction = true;
    },
    cardcamera () {
      var _this = this;
      var cardcamera = window.api && window.api.require('cardcamera');
      cardcamera.frontIdCard({
      }, function (ret, err) {
        if (ret.status) {
          _this.IDFace(ret.data);
        } else {
          alert(err);
        }
      });
    },

    submit () {
      this.isLoading = true;
      if (!this.form.fullName) {
        this.$toast('请输入真实姓名');
        return;
      }
      if (!this.form.IDNumber) {
        this.$toast('请输入身份证号码');
        return;
      }
      var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
      if (!reg.test(this.form.IDNumber)) {
        this.$toast('请输入正确的身份证号码');
        return;
      }
      if (!this.form.frontImg) {
        this.$toast('请上传正面照片');
        return;
      }
      if (!this.form.reverseImg) {
        this.$toast('请上传反面照片');
        return;
      }
      this.form.sex = this.sexValue;
      this.$API.user.memberCertSave(this.form).then(res => {
        if (!res.code) {
          this.$dialog.alert({
            title: '温馨提醒',
            message: '恭喜你认证成功!',
            confirmButtonText: '完 成'
          }).then(() => {
            this.$router.push({ path: '/authentication', query: { type: 2 } });
          });
          this.isLoading = false;
        } else {
          this.$toast(res.message);
          this.isLoading = false;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.authentication {
  display: flex;
  height: 100%;
  flex-direction: column;
  .content {
    flex: 1;
    overflow: auto;
    .id-name {
      font-size: 32px;
      color: #333;
      padding: 20px 40px;
    }
    .sex {
      background-color: #fff;
      display: flex;
      padding: 26px 30px;
      color: #323233;
      border: 2px solid #eee;
      font-size: 28px;
      justify-content: space-between;
      border-radius: 8px;
      .label {
        width: 140px;
      }
      .name {
        color: #96989a;
        position: relative;
        padding-right: 30px;
        &::after {
          content: '';
          display: inline-block;
          width: 14px;
          height: 24px;
          position: absolute;
          top: 50%;
          right: 0;
          margin-top: -12px;
          background-image: url('/static/images/icon-arrow-right.png');
          background-position: center center;
          background-repeat: no-repeat;
          background-size: 14px 24px;
          vertical-align: middle;
          margin-left: 32px;
        }
      }
      .name.active {
        color: #5788ff;
      }
    }
    .id-images {
      background-color: #fff;
    }
    .id-from {
      background-color: #fff;
      padding: 5px 40px;
      .van-field__control {
        color: #5788ff;
      }
    }
    .tis {
      padding: 29px 40px;
      text-align: left;
      font-size: 28px;
      color: #717070;
    }
    .positive-reverse {
      display: flex;
      justify-content: space-between;
      padding: 0 20px 30px;
    }
    .positive,
    .reverse {
      position: relative;
      margin: 0 20px;
      width: 50%;
      .loading {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 60px;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
      }
      .failed {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 60px;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        z-index: 999;
      }
      .camera {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 60px;
        right: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f4f8fe;
        pointer-events: none;
        &::after {
          content: '';
          display: block;
          width: 244px;
          height: 142px;
          // background-image: url('/static/images/icon-frontImg.png');
          background-repeat: no-repeat;
          background-position: center center;
          background-repeat: no-repeat;
          background-size: 244px 142px;
        }
      }
      .text {
        padding: 14px 0 14px;
        font-size: 24px;
        text-align: center;
        color: #fff;
        background-color: #125dff;
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
      }
      .images.hidden {
        overflow: hidden;
      }
      .images {
        object-fit: contain;
        background-color: #f4f8fe;
        height: 224px;
        position: relative;
        object-fit: cover;
        img {
          width: 100%;
        }
        .uploader {
          position: absolute;
          width: 100%;
          height: 100%;
          /deep/ .van-uploader__wrapper {
            width: 100%;
            height: 100%;
          }
          /deep/ .van-uploader__upload {
            width: 100%;
            height: 100%;
            background: transparent;
          }
          /deep/ .van-uploader__upload-icon {
            display: none;
          }
          /deep/ .van-uploader__preview {
            width: 100%;
            height: 100%;
            margin: 0;
            .van-uploader__preview-image {
              width: 100%;
              height: 100%;
              border-bottom-right-radius: 0 !important;
              border-bottom-left-radius: 0 !important;
            }
          }
        }
      }
    }
    .positive {
      .camera {
        &::after {
          background-image: url('/static/img/icon-frontImg.png');
        }
      }
    }
    .reverse {
      .camera {
        &::after {
          background-image: url('/static/img/icon-reverseImg.png');
        }
      }
    }
  }
  .submitBtn {
    margin: 25px 40px;
    .btn {
      background-color: #fff;
      width: 100%;
      height: 100px;
      line-height: 100px;
      .van-button__text {
        color: #125dff;
        font-size: 34px;
      }
    }
  }
}
</style>
